package gen

import (
	"encoding/json"
	"fmt"
	"net/http"
)

type H map[string]interface{}

type Context struct {
	// origin objects
	Response http.ResponseWriter
	Request  *http.Request
	// 请求信息
	Path   string
	Method string
	// 返回信息
	StatusCode int
}

// 内部函数,生成一个上下文结构体
func newContext(w http.ResponseWriter, r *http.Request) *Context {
	return &Context{
		Response:   w,
		Request:    r,
		Path:       r.URL.Path,
		Method:     r.Method,
		StatusCode: 0,
	}
}

// 获取 POST 表单数据(单条记录)
func (self *Context) PostForm(key string) string {
	return self.Request.FormValue(key)
}

// 获取 url 路径中的参数(单条记录)
func (self *Context) Query(key string) string {
	return self.Request.URL.Query().Get(key)
}

// 设置状态码
func (self *Context) Status(code int) {
	self.StatusCode = code
	self.Response.WriteHeader(code)
}

// 设置返回头
func (self *Context) SetHeader(key string, value string) {
	self.Response.Header().Set(key, value)
}

// 返回字符串
func (self *Context) String(code int, format string, values ...interface{}) {
	self.SetHeader("Context-Type", "text/plain")
	self.Status(code)
	self.Response.Write([]byte(fmt.Sprintf(format, values...)))
}

// 返回 Json
func (self *Context) JSON(code int, obj interface{}) {
	self.SetHeader("Context-Type", "application/json")
	self.Status(code)

	encoder := json.NewEncoder(self.Response)
	if err := encoder.Encode(obj); err != nil {
		panic(err)
	}
}

// 返回数据 byte 类型
func (self *Context) Data(code int, data []byte) {
	self.Status(code)
	self.Response.Write(data)
}

// 返回 Html 文件
func (self *Context) HTML(code int, html string) {
	self.SetHeader("Context-Type", "text/html")
	self.Status(code)
	self.Response.Write([]byte(html))
}
